﻿using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Xml;

namespace Catchbase.Service.API
{
    public class JsonHelper
    {
        public virtual T Read<T>(IStreamProvider provider)
        {
            Debug.Assert(provider != null);
            string json;
            var stream = provider.GetStream();
            using(var reader = new StreamReader(stream))
            {
                json = reader.ReadToEnd();
            }
            provider.ReleaseStream(stream);
            return DeSerialize<T>(json);
        }

        public virtual void Write<T>(IStreamProvider provider, T item) where T : class
        {
            Debug.Assert(provider != null);
            Debug.Assert(item != null);
            string json = Serialize(item);
            var stream = provider.GetStream();
            using(var writer = new StreamWriter(stream))
            {
                writer.Write(json);
            }
            provider.ReleaseStream(stream);
        }

        private static string Serialize<T>(T instance) where T : class
        {
            var serializer = new DataContractJsonSerializer(typeof(T));
            using (var stream = new MemoryStream())
            {
                serializer.WriteObject(stream, instance);
                return Encoding.UTF8.GetString(stream.ToArray());
            }
        }

        private static T DeSerialize<T>(string json)
        {
            var serializer = new DataContractJsonSerializer(typeof(T));
            using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
            {
                return (T)serializer.ReadObject(stream);
            }
        }
    }
}